package cn.edu.imut.util;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * DBUtil - 一个用于数据库连接和资源管理的工具类
 */
public class DBUtil {
    // 数据库配置信息
    private static final String URL = "jdbc:mysql://localhost:3306/GlamshopDB?useSSL=false&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "abc123";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver"; // MySQL JDBC 驱动

    // 静态代码块加载 JDBC 驱动
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            System.err.println("数据库驱动加载失败：" + e.getMessage());
            throw new RuntimeException(e); // 将异常封装为运行时异常抛出
        }
    }


    /**
     * 获取数据库连接
     *
     * @return Connection 对象
     */
    @SneakyThrows
    public static Connection getConnection() {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    /**
     * 关闭数据库资源
     *
     * @param connection Connection 对象
     * @param statement  Statement 对象
     * @param resultSet  ResultSet 对象
     */
    @SneakyThrows
    public static void close(Connection connection, Statement statement, ResultSet resultSet) {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    /**
     * 关闭数据库资源（重载方法，不包括 ResultSet）
     *
     * @param connection Connection 对象
     * @param statement  Statement 对象
     */
    public static void close(Connection connection, Statement statement) {
        close(connection, statement, null);
    }

    /**
     * 测试数据库连接
     */
    public static void main(String[] args) {
        Connection connection = getConnection();
        if (connection != null) {
            System.out.println("数据库连接成功！");
            close(connection, null, null);
        } else {
            System.out.println("数据库连接失败！");
        }
    }
}
